﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraReports.UI;
using OilDB;

namespace MainApp
{
    public partial class CashReport : DevExpress.XtraEditors.XtraUserControl
    {
        Guid allStores = Guid.Empty;
        DataServices data;

        Dictionary<Guid, DevExpress.XtraLayout.LayoutControlItem> labels = new Dictionary<Guid, DevExpress.XtraLayout.LayoutControlItem>();

        Dictionary<Guid, DevExpress.XtraEditors.SpinEdit> spInitials = new Dictionary<Guid, DevExpress.XtraEditors.SpinEdit>();
        Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem> layInitials = new Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem>();

        Dictionary<Guid, DevExpress.XtraEditors.SpinEdit> spImports = new Dictionary<Guid, DevExpress.XtraEditors.SpinEdit>();
        Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem> layImports = new Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem>();

        Dictionary<Guid, DevExpress.XtraEditors.SpinEdit> spExports = new Dictionary<Guid, DevExpress.XtraEditors.SpinEdit>();
        Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem> layExports = new Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem>();

        Dictionary<Guid, DevExpress.XtraEditors.SpinEdit> spTotals = new Dictionary<Guid, DevExpress.XtraEditors.SpinEdit>();
        Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem> layTotals = new Dictionary<Guid, DevExpress.XtraLayout.BaseLayoutItem>();

        List<Guid> productList = new List<Guid>();

        CashPrintReport printReport = new CashPrintReport();
        Dictionary<Guid, XRLabel> printLabels = new Dictionary<Guid, XRLabel>();
        Dictionary<Guid, XRLabel> printInitials = new Dictionary<Guid, XRLabel>();
        Dictionary<Guid, XRLabel> printImports = new Dictionary<Guid, XRLabel>();
        Dictionary<Guid, XRLabel> printExports = new Dictionary<Guid, XRLabel>();
        Dictionary<Guid, XRLabel> printTotals = new Dictionary<Guid, XRLabel>();

        public enum PeriodType
        {
            [Description("Theo ngày")]
            byDay,
            [Description("Theo tháng")]
            byMonth,
            [Description("Theo năm")]
            byYear,
            [Description("Tùy chọn")]
            byCustom
        }

        public void showPrintPreView()
        {
            printReport.BeginUpdate();
            printReport.txtTitle.Text = CashStatisticTitle.Text;
            printReport.txtSell.Text = spSell.Text;
            printReport.txtPayment.Text = spPayment.Text;
            printReport.txtDebt.Text = spDebt.Text;
            printReport.txtExpense.Text = spExpense.Text;
            printReport.txtTotal.Text = spTotal.Text;

            foreach (Guid item in productList)
            {
                printLabels[item].Text = labels[item].Text;
                printInitials[item].Text = spInitials[item].Text;
                printImports[item].Text = spImports[item].Text;
                printExports[item].Text = spExports[item].Text;
                printTotals[item].Text = spTotals[item].Text;
            }
            //updateProductforPrintReport();
            printReport.EndUpdate();
            printReport.CreateDocument();
            printReport.ShowPreview();
        }

        private void updateProductforPrintReport()
        {
            int count = 0;
            XRLabel newlabel = null;
            float newWidth = (printReport.PageWidth - printReport.Margins.Left - printReport.Margins.Right) / (productList.Count + 1);
            printReport.txtHH.WidthF = newWidth;
            printReport.txtInitial.WidthF = newWidth;
            printReport.txtImport.WidthF = newWidth;
            printReport.txtExport.WidthF = newWidth;
            printReport.txtTotals.WidthF = newWidth;
            //foreach (Guid item in productList)
            for (int i = productList.Count - 1; i >= 0; i--)
            {
                Guid item = productList[i];
                count++;

                //label
                newlabel = newPrintXRLabel(count, item, printReport.txtHH);                
                printLabels[item] = newlabel;


                //Tổng đầu
                newlabel = newPrintXRLabel(count, item, printReport.txtInitial);
                printInitials[item] = newlabel;

                //Nhập
                newlabel = newPrintXRLabel(count, item, printReport.txtImport);
                printImports[item] = newlabel;

                //Xuất
                newlabel = newPrintXRLabel(count, item, printReport.txtExport);
                printExports[item] = newlabel;

                //Tổng cuối
                newlabel = newPrintXRLabel(count, item, printReport.txtTotals);
                printTotals[item] = newlabel;
            }
            
        }

        private XRLabel newPrintXRLabel(int position, Guid item, XRLabel sample)
        {
            XRLabel newlabel = new XRLabel();

            newlabel.Name = sample.Name + labels[item].Text;
            newlabel.BackColor = sample.BackColor;
            newlabel.Borders = sample.Borders;
            newlabel.Font = sample.Font;            
            newlabel.Padding = sample.Padding;
            newlabel.SizeF = sample.SizeF;
            newlabel.StylePriority.UseBackColor = sample.StylePriority.UseBackColor;
            newlabel.StylePriority.UseBorders = sample.StylePriority.UseBackColor;
            newlabel.StylePriority.UseFont = sample.StylePriority.UseBackColor;
            newlabel.StylePriority.UseTextAlignment = sample.StylePriority.UseBackColor;

            //newlabel.Text = labels[item].Text;
            newlabel.LocationF = sample.LocationF;
            newlabel.LeftF += position * sample.WidthF;

            newlabel.TextAlignment = sample.TextAlignment;
            printReport.Detail.Controls.Add(newlabel);
            newlabel.Visible = true;            
            return newlabel;
        }

        public CashReport()
        {
            InitializeComponent();
            radCashType.Properties.Items.Clear();
            radCashType.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(PeriodType.byDay, "Theo ngày"));
            radCashType.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(PeriodType.byMonth, "Theo tháng"));
            radCashType.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(PeriodType.byYear, "Theo năm"));
            radCashType.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(PeriodType.byCustom, "Tùy chọn"));


            cbMonth.Properties.Items.Clear();
            for (int i = 1; i <= 12; i++)
            {
                cbMonth.Properties.Items.Add(i);
            }
            cbYear.Properties.Items.Clear();
            for (int i = 1990; i <= 2060; i++)
            {
                cbYear.Properties.Items.Add(i);
            }

            radCashType.SelectedIndex = 0;
        }

        private void radCashType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch ((PeriodType)radCashType.EditValue)
            {
                case PeriodType.byDay:
                    cbDate.Visible = true;
                    cbMonth.Visible = false;
                    lblSeparator.Visible = false;
                    cbYear.Visible = false;
                    cbDate1.Visible = false;
                    cbDate2.Visible = false;
                    break;
                case PeriodType.byMonth:
                    cbDate.Visible = false;
                    cbMonth.Visible = true;
                    lblSeparator.Visible = true;
                    cbYear.Visible = true;
                    cbDate1.Visible = false;
                    cbDate2.Visible = false;
                    cbYear.Top = cbMonth.Top;
                    cbYear.Left = lblSeparator.Left + lblSeparator.Width + (lblSeparator.Left - cbMonth.Left - cbMonth.Width);
                    break;
                case PeriodType.byYear:
                    cbDate.Visible = false;
                    cbMonth.Visible = false;
                    lblSeparator.Visible = false;
                    cbYear.Visible = true;
                    cbDate1.Visible = false;
                    cbDate2.Visible = false;
                    cbYear.Left = cbMonth.Left;
                    cbYear.Top = cbMonth.Top + cbMonth.Height + (cbMonth.Top - cbDate.Top - cbDate.Height);
                    break;
                case PeriodType.byCustom:
                    cbDate.Visible = false;
                    cbMonth.Visible = false;
                    lblSeparator.Visible = false;
                    cbYear.Visible = false;
                    cbDate1.Visible = true;
                    cbDate2.Visible = true;
                    break;
                default:
                    break;
            }
        }

        private DateTime getBeginDate()
        {
            DateTime r = new DateTime(1990, 6, 26);
            try
            {
                switch ((PeriodType)radCashType.EditValue)
                {
                    case PeriodType.byDay:
                        r = (DateTime)cbDate.EditValue;
                        break;
                    case PeriodType.byMonth:
                        r = new DateTime((int)cbYear.EditValue, (int)cbMonth.EditValue, 1);
                        break;
                    case PeriodType.byYear:
                        r = new DateTime((int)cbYear.EditValue, 1, 1);
                        break;
                    case PeriodType.byCustom:
                        r = (DateTime)cbDate1.EditValue;
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {
            }
            return r;
        }

        private DateTime getEndDate()
        {
            DateTime r = new DateTime(1990, 6, 26);
            try
            {
                switch ((PeriodType)radCashType.EditValue)
                {
                    case PeriodType.byDay:
                        r = ((DateTime)cbDate.EditValue).AddDays(1);
                        break;
                    case PeriodType.byMonth:
                        r = (new DateTime((int)cbYear.EditValue, (int)cbMonth.EditValue, 1)).AddMonths(1);
                        break;
                    case PeriodType.byYear:
                        r = (new DateTime((int)cbYear.EditValue, 1, 1)).AddYears(1);
                        break;
                    case PeriodType.byCustom:
                        r = ((DateTime)cbDate2.EditValue).AddDays(1);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {
            }
            return r;
        }

        private void setBeginDate(DateTime value)
        {
            cbDate.EditValue = value;
            cbYear.EditValue = value.Year;
            cbMonth.EditValue = value.Month;
            cbDate1.EditValue = value;
        }

        public void updateProducts()
        {
            CashStatisticControl.BeginUpdate();
            clearProducts();

            //DevExpress.XtraLayout.LayoutControlItem newLay = null;
            //DevExpress.XtraEditors.SpinEdit newEdit = null;



            productList.Clear();

            foreach (DataSetOilManagement.ProductsRow row in data.DsOil.Products)
            {
                if (row.IsNull(data.DsOil.Products.TypeColumn))
                {
                    productList.Add(row.ID);
                    //Tên hàng hóa
                    newProductLabel(row);

                    //Tồn đầu
                    newInitialEdit(row);

                    //Nhập
                    newImportEdit(row);

                    //Xuất
                    newExportEdit(row);

                    // Tổng cộng
                    newTotalEdit(row); 
                }
            }

            updateProductforPrintReport();
            CashStatisticControl.EndUpdate();
        }

        private void newTotalEdit(DataSetOilManagement.ProductsRow row)
        {
            DevExpress.XtraEditors.SpinEdit newEdit = new DevExpress.XtraEditors.SpinEdit();
            newEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0 });
            //newEdit.Location = new System.Drawing.Point(343, 287);
            newEdit.Name = "spTotal" + row.ProductName;
            newEdit.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 11F, FontStyle.Bold);
            newEdit.Properties.Appearance.Options.UseFont = true;
            //newEdit.Size = new System.Drawing.Size(318, 23);
            newEdit.StyleController = CashStatisticControl;
            newEdit.TabIndex = 10;
            newEdit.Properties.Buttons.Clear();
            newEdit.Properties.ReadOnly = true;
            newEdit.BackColor = Color.Silver;
            newEdit.Properties.DisplayFormat.Assign(spSample.Properties.DisplayFormat);
            newEdit.Properties.EditFormat.Assign(spSample.Properties.EditFormat);

            CashStatisticControl.Controls.Add(newEdit);
            spTotals[row.ID] = newEdit;

            DevExpress.XtraLayout.LayoutControlItem newLay = groupNhapXuat.AddItem(newEdit.Name, newEdit);
            newLay.TextVisible = false;
            newLay.Move(lblTotal, DevExpress.XtraLayout.Utils.InsertType.Right);
            layTotals[row.ID] = newLay;
        }

        private void newExportEdit(DataSetOilManagement.ProductsRow row)
        {
            DevExpress.XtraEditors.SpinEdit newEdit = new DevExpress.XtraEditors.SpinEdit();
            newEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0 });
            //newEdit.Location = new System.Drawing.Point(343, 287);
            newEdit.Name = "spExport" + row.ProductName;
            newEdit.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
            newEdit.Properties.Appearance.Options.UseFont = true;
            //newEdit.Size = new System.Drawing.Size(318, 23);
            newEdit.StyleController = CashStatisticControl;
            newEdit.TabIndex = 10;
            newEdit.Properties.Buttons.Clear();
            newEdit.Properties.ReadOnly = true;
            newEdit.Properties.DisplayFormat.Assign(spSample.Properties.DisplayFormat);
            newEdit.Properties.EditFormat.Assign(spSample.Properties.EditFormat);

            CashStatisticControl.Controls.Add(newEdit);
            spExports[row.ID] = newEdit;

            DevExpress.XtraLayout.LayoutControlItem newLay = groupNhapXuat.AddItem(newEdit.Name, newEdit);
            newLay.TextVisible = false;
            newLay.Move(lblExport, DevExpress.XtraLayout.Utils.InsertType.Right);
            layExports[row.ID] = newLay;
        }

        private void newImportEdit(DataSetOilManagement.ProductsRow row)
        {
            DevExpress.XtraEditors.SpinEdit newEdit = new DevExpress.XtraEditors.SpinEdit();
            newEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0 });
            //newEdit.Location = new System.Drawing.Point(343, 287);
            newEdit.Name = "spImport" + row.ProductName;
            newEdit.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
            newEdit.Properties.Appearance.Options.UseFont = true;
            //newEdit.Size = new System.Drawing.Size(318, 23);
            newEdit.StyleController = CashStatisticControl;
            newEdit.TabIndex = 10;
            newEdit.Properties.Buttons.Clear();
            newEdit.Properties.ReadOnly = true;
            newEdit.Properties.DisplayFormat.Assign(spSample.Properties.DisplayFormat);
            newEdit.Properties.EditFormat.Assign(spSample.Properties.EditFormat);

            CashStatisticControl.Controls.Add(newEdit);
            spImports[row.ID] = newEdit;

            DevExpress.XtraLayout.LayoutControlItem newLay = groupNhapXuat.AddItem(newEdit.Name, newEdit);
            newLay.TextVisible = false;
            newLay.Move(lblImport, DevExpress.XtraLayout.Utils.InsertType.Right);
            layImports[row.ID] = newLay;
        }

        private void newInitialEdit(DataSetOilManagement.ProductsRow row)
        {
            DevExpress.XtraEditors.SpinEdit newEdit = new DevExpress.XtraEditors.SpinEdit();
            newEdit.EditValue = new decimal(new int[] { 0, 0, 0, 0 });
            //newEdit.Location = new System.Drawing.Point(343, 287);
            newEdit.Name = "spInitial" + row.ProductName;
            newEdit.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 10F);
            newEdit.Properties.Appearance.Options.UseFont = true;
            //newEdit.Size = new System.Drawing.Size(318, 23);
            newEdit.StyleController = CashStatisticControl;
            newEdit.TabIndex = 10;
            newEdit.Properties.Buttons.Clear();
            newEdit.Properties.ReadOnly = true;
            newEdit.Properties.DisplayFormat.Assign(spSample.Properties.DisplayFormat);
            newEdit.Properties.EditFormat.Assign(spSample.Properties.EditFormat);

            CashStatisticControl.Controls.Add(newEdit);
            spInitials[row.ID] = newEdit;

            DevExpress.XtraLayout.LayoutControlItem newLay = groupNhapXuat.AddItem(newEdit.Name, newEdit);
            newLay.TextVisible = false;
            newLay.Move(lblInitial, DevExpress.XtraLayout.Utils.InsertType.Right);
            layInitials[row.ID] = newLay;
        }

        private void newProductLabel(DataSetOilManagement.ProductsRow row)
        {
            DevExpress.XtraLayout.SimpleLabelItem newlabel = new DevExpress.XtraLayout.SimpleLabelItem();
            newlabel.Text = row.ProductName;
            newlabel.AppearanceItemCaption.Font = lblName.AppearanceItemCaption.Font;

            labels[row.ID] = groupNhapXuat.AddItem(newlabel);
            newlabel.Move(lblName, DevExpress.XtraLayout.Utils.InsertType.Right);
            newlabel.AppearanceItemCaption.Options.UseTextOptions = true;
            newlabel.AppearanceItemCaption.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
            //newlabel.Size = new Size(200, newlabel.Size.Height);
        }

        private void clearProductsforPrintReport()
        {
            foreach (XRLabel item in printLabels.Values)
            {
                printReport.Detail.Controls.Remove(item);
            }
            printLabels.Clear();
            foreach (XRLabel item in printInitials.Values)
            {
                printReport.Detail.Controls.Remove(item);
            }
            printInitials.Clear();
            foreach (XRLabel item in printImports.Values)
            {
                printReport.Detail.Controls.Remove(item);
            }
            printImports.Clear();
            foreach (XRLabel item in printExports.Values)
            {
                printReport.Detail.Controls.Remove(item);
            }
            printExports.Clear();
            foreach (XRLabel item in printTotals.Values)
            {
                printReport.Detail.Controls.Remove(item);
            }
            printTotals.Clear();
        }
        private void clearProducts()
        {
            clearProductsforPrintReport();
            foreach (DevExpress.XtraLayout.LayoutControlItem item in labels.Values)
            {
                groupNhapXuat.Remove(item);
            }
            labels.Clear();
            foreach (DevExpress.XtraLayout.BaseLayoutItem item in layInitials.Values)
            {
                groupNhapXuat.Remove(item);
            }
            layInitials.Clear();
            foreach (DevExpress.XtraLayout.BaseLayoutItem item in layImports.Values)
            {
                groupNhapXuat.Remove(item);
            }
            layImports.Clear();
            foreach (DevExpress.XtraLayout.BaseLayoutItem item in layExports.Values)
            {
                groupNhapXuat.Remove(item);
            }
            layExports.Clear();
            foreach (DevExpress.XtraLayout.BaseLayoutItem item in layTotals.Values)
            {
                groupNhapXuat.Remove(item);
            }
            layTotals.Clear();
            foreach (DevExpress.XtraEditors.SpinEdit item in spInitials.Values)
            {
                CashStatisticControl.Controls.Remove(item);
            }
            spInitials.Clear();
            foreach (DevExpress.XtraEditors.SpinEdit item in spImports.Values)
            {
                CashStatisticControl.Controls.Remove(item);
            }
            spImports.Clear();
            foreach (DevExpress.XtraEditors.SpinEdit item in spExports.Values)
            {
                CashStatisticControl.Controls.Remove(item);
            }
            spExports.Clear();
            foreach (DevExpress.XtraEditors.SpinEdit item in spTotals.Values)
            {
                CashStatisticControl.Controls.Remove(item);
            }
            spTotals.Clear();

            productList.Clear();
        }

        public void updateStores()
        {
            dataSetOilManagement.Stores.Clear();
            dataSetOilManagement.Stores.AddStoresRow(allStores, "Tất cả", "", "");
            foreach (DataSetOilManagement.StoresRow row in data.DsOil.Stores)
            {
                dataSetOilManagement.Stores.Rows.Add(row.ItemArray);
            }
            //cbStores.EditValue = allStores;
        }

        public void updateReport()
        {
            if (data == null)
            {
                return;
            }

            data.SellStatisticsAllAdapter.Fill(dataSetOilManagement.SellStatistics_All, BeginDate, EndDate);
            data.DebtStatisticsAdapter.Fill(dataSetOilManagement.DebtStatistics, BeginDate, EndDate);
            data.PaymentStatisticAdapter.Fill(dataSetOilManagement.PaymentStatistics, BeginDate, EndDate);
            data.ExpensesStatisticsAdapter.Fill(dataSetOilManagement.ExpenseStatistics, BeginDate, EndDate);

            data.ImportStatisticsAdapter.Fill(dataSetOilManagement.ImportStatistics, BeginDate, EndDate);
            data.ImportStatisticsAdapter.Fill(dataSetOilManagementInitial.ImportStatistics, null, BeginDate);

            data.ExportStatisticsAdapter.Fill(dataSetOilManagement.ExportStatistics, BeginDate, EndDate);
            data.ExportStatisticsAdapter.Fill(dataSetOilManagementInitial.ExportStatistics, null, BeginDate);

            decimal sumTotal = 0, sumDebt = 0;
            decimal sumPayment = 0;
            decimal sumExpense = 0;
            Dictionary<Guid, decimal> sumbyProduct = new Dictionary<Guid, decimal>();

            //Tính tổng cho các statistic, dùng khi người dùng chọn xem tất cả các cửa hàng

            //Số tiền bán được
            foreach (DataSetOilManagement.SellStatistics_AllRow row in dataSetOilManagement.SellStatistics_All)
            {
                sumTotal += row.Total;                
            }
            dataSetOilManagement.SellStatistics_All.AddSellStatistics_AllRow(allStores, sumTotal);

            //Số tiền nợ lại
            foreach (DataSetOilManagement.DebtStatisticsRow row in dataSetOilManagement.DebtStatistics)
            {
                sumDebt += row.TotalDebt;
            }
            dataSetOilManagement.DebtStatistics.AddDebtStatisticsRow(allStores, sumDebt);

            //Số tiền thu nợ được
            foreach (DataSetOilManagement.PaymentStatisticsRow row in dataSetOilManagement.PaymentStatistics)
            {
                sumPayment += row.TotalAmount;
            }
            dataSetOilManagement.PaymentStatistics.AddPaymentStatisticsRow(allStores, sumPayment);

            //Số tiền chi tiêu
            foreach (DataSetOilManagement.ExpenseStatisticsRow row in dataSetOilManagement.ExpenseStatistics)
            {
                sumExpense += row.TotalExpensed;
            }
            dataSetOilManagement.ExpenseStatistics.AddExpenseStatisticsRow(allStores, sumExpense);

            //Tổng số xăng nhập
            foreach (Guid product in productList)
            {
                sumbyProduct[product] = 0;
            }
            foreach (DataSetOilManagement.ImportStatisticsRow row in dataSetOilManagement.ImportStatistics)
            {
                sumbyProduct[row.Product] += row.TotalAmount;
            }
            foreach (Guid product in productList)
            {
                dataSetOilManagement.ImportStatistics.AddImportStatisticsRow(allStores, product, sumbyProduct[product]);
            }

            //Tổng số xăng nhập trước khi khoảng thời gian chọn (để tính tồn đầu)
            foreach (Guid product in productList)
            {
                sumbyProduct[product] = 0;
            }
            foreach (DataSetOilManagement.ImportStatisticsRow row in dataSetOilManagementInitial.ImportStatistics)
            {
                sumbyProduct[row.Product] += row.TotalAmount;
            }
            foreach (Guid product in productList)
            {
                dataSetOilManagementInitial.ImportStatistics.AddImportStatisticsRow(allStores, product, sumbyProduct[product]);
            }

            //Tổng số xăng bán ra
            foreach (Guid product in productList)
            {
                sumbyProduct[product] = 0;
            }
            foreach (DataSetOilManagement.ExportStatisticsRow row in dataSetOilManagement.ExportStatistics)
            {
                sumbyProduct[row.Product] += row.TotalAmount;
            }
            foreach (Guid product in productList)
            {
                dataSetOilManagement.ExportStatistics.AddExportStatisticsRow(allStores, product, sumbyProduct[product]);
            }

            //Tổng số xăng bán ra trước thời điểm chọn (để tính tồn đầu)
            foreach (Guid product in productList)
            {
                sumbyProduct[product] = 0;
            }
            foreach (DataSetOilManagement.ExportStatisticsRow row in dataSetOilManagementInitial.ExportStatistics)
            {
                sumbyProduct[row.Product] += row.TotalAmount;
            }
            foreach (Guid product in productList)
            {
                dataSetOilManagementInitial.ExportStatistics.AddExportStatisticsRow(allStores, product, sumbyProduct[product]);
            }

            if (cbStores.EditValue != null)
            {
                updateReportByStore((Guid)cbStores.EditValue);
            }
        }

        private void updateReportByStore(Guid store)
        {
            string title = "Thống kê ";
            DataSetOilManagement.StoresRow rowStore = data.DsOil.Stores.FindByID(store);
            if (rowStore != null)
            {
                title += rowStore.StoreName;
            }
            switch ((PeriodType)radCashType.EditValue)
            {
                case PeriodType.byDay:
                    title += " ngày " + getBeginDate().ToString("dd/MM/yyyy");
                    break;
                case PeriodType.byMonth:
                    title += " tháng " + getBeginDate().ToString("MM/yyyy");
                    break;
                case PeriodType.byYear:
                    title += " năm " + getBeginDate().ToString("yyyy");
                    break;
                case PeriodType.byCustom:
                    title += String.Format(" từ {0:dd/MM/yyyy} đến {1:dd/MM/yyyy}", getBeginDate(), getEndDate().AddDays(-1));
                    break;
                default:
                    break;
            }
            CashStatisticTitle.Text = title;
            #region Báo cáo thu chi
            DataSetOilManagement.SellStatistics_AllRow sellRow = dataSetOilManagement.SellStatistics_All.FindByStoreID(store);
            DataSetOilManagement.DebtStatisticsRow debtRow = dataSetOilManagement.DebtStatistics.FindByStoreID(store);
            DataSetOilManagement.ExpenseStatisticsRow expenseRow = dataSetOilManagement.ExpenseStatistics.FindByStoreID(store);
            DataSetOilManagement.PaymentStatisticsRow paymentRow = dataSetOilManagement.PaymentStatistics.FindByStoreID(store);

            decimal sell = 0, debt = 0, expense = 0, payment = 0;
            //Tính số tiền bán được, và còn nợ lại
            if (sellRow != null)
            {
                sell = sellRow.Total;
            }

            if (debtRow != null)
            {
                debt = debtRow.TotalDebt;
            }

            //Số tiền chi tiêu
            if (expenseRow != null)
            {
                expense = expenseRow.TotalExpensed;
            }

            //Số tiền thu nợ được
            if (paymentRow != null)
            {
                payment = paymentRow.TotalAmount;
            }

            spSell.EditValue = sell;
            spDebt.EditValue = debt;
            spExpense.EditValue = expense;
            spPayment.EditValue = payment;
            spTotal.EditValue = sell + payment - debt - expense;

            #endregion

            decimal importInitial, exportInitial, import, export;
            DataSetOilManagement.ImportStatisticsRow importRow, importInitialRow;
            DataSetOilManagement.ExportStatisticsRow exportRow, exportInitialRow;
            foreach (Guid product in productList)
            {
                importRow = dataSetOilManagement.ImportStatistics.FindByStoreIDProduct(store, product);
                importInitialRow = dataSetOilManagementInitial.ImportStatistics.FindByStoreIDProduct(store, product);
                exportRow = dataSetOilManagement.ExportStatistics.FindByStoreIDProduct(store, product);
                exportInitialRow = dataSetOilManagementInitial.ExportStatistics.FindByStoreIDProduct(store, product);

                import = importRow != null ? importRow.TotalAmount : 0;
                importInitial = importInitialRow != null ? importInitialRow.TotalAmount : 0;
                export = exportRow != null ? exportRow.TotalAmount : 0;
                exportInitial = exportInitialRow != null ? exportInitialRow.TotalAmount : 0;

                spInitials[product].EditValue = importInitial - exportInitial;
                spImports[product].EditValue = import;
                spExports[product].EditValue = export;
                spTotals[product].EditValue = importInitial + import - exportInitial - export;
            }
        }

        private void setData(DataServices value)
        {
            data = value;
        }

        public DateTime BeginDate { get { return getBeginDate(); } set { setBeginDate(value); } }
        public DateTime EndDate { get { return getEndDate(); } }
        public DataServices Data { get { return data; } set { setData(value); } }

        private void button1_Click(object sender, EventArgs e)
        {
            updateProducts();
        }

        private void Option_Changed(object sender, EventArgs e)
        {
            if (cbStores.EditValue != null)
            {
                updateReport();
            }
        }

        private void cbStores_EditValueChanged(object sender, EventArgs e)
        {
            if (cbStores.EditValue != null)
            {
                updateReportByStore((Guid)cbStores.EditValue);
            }
        }

        private void CashReport_Load(object sender, EventArgs e)
        {

            cbMonth.EditValue = DateTime.Today.Month;
            cbYear.EditValue = DateTime.Today.Year;
            cbDate.EditValue = DateTime.Today;
            cbDate1.EditValue = DateTime.Today;
            cbDate2.EditValue = DateTime.Today;

            cbDate.EditValueChanged += Option_Changed;
            cbMonth.EditValueChanged += Option_Changed;
            cbYear.EditValueChanged += Option_Changed;
            radCashType.EditValueChanged += Option_Changed;
            cbStores.EditValueChanged += cbStores_EditValueChanged;
            cbDate1.EditValueChanged += Option_Changed;
            cbDate2.EditValueChanged += Option_Changed;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            CashStatisticControl.ShowPrintPreview();
        }

        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            showPrintPreView();
            
        }

        private void cbStores_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.OldValue == null)
            {
                updateReport();
            }
        }
    }
}
